# coding: utf-8

"""
@version: python3.6
@author: 噢啦嘿嘿
@contact: jian.zhou@360che.com
@software: PyCharm
@file: collect_pro.py
@time: 2021/4/14 10:13
"""

import time
from datetime import datetime

from dateutil.relativedelta import relativedelta
from sqlalchemy import func, desc
from sqlalchemy import or_

from application import db
from application.libs import const
from application.libs.enum import demand
from application.models.mantis_models import MantisBugTable, MantisProjectTable, MantisUserTable
from application.models.models import Collect, ProjectRelevance


def get_collect_pro(char_info):
    Collect_parm = [Collect.status != 0]
    Bug_parm = [MantisBugTable.resolution != 60, MantisBugTable.resolution != 70,
                MantisBugTable.resolution != 90]  # 有效bug
    group_name = char_info['group_name']
    pro_parm = []
    # if group_name == '内容·运营':
    #     Collect_parm.append(or_(Collect.group == '互动',
    #                             Collect.group == '资讯')
    #                         )
    #     pro_parm.append(or_(ProjectRelevance.qa_gname == '互动',
    #                         ProjectRelevance.qa_gname == '资讯')
    #                     )
    # else:
    pro_parm.append(ProjectRelevance.qa_gname == group_name)
    Collect_parm.append(Collect.group == group_name
                            )
    # 项目情况
    date_time = _day(char_info['radio'])
    s_date = date_time[0]
    e_date = date_time[1]
    # print(s_date, e_date)
    Collect_parm.append(or_(Collect.begindate >= s_date, Collect.onlinedate >= s_date, Collect.enddate >= s_date))
    Collect_parm.append(or_(Collect.begindate <= e_date, Collect.onlinedate <= e_date, Collect.enddate <= e_date))
    # Collect_parm.append(Collect.onlinedate <= e_date)
    page_data = db.session.query(Collect).filter(*Collect_parm).all()

    # bug情况
    pro_l = db.session.query(ProjectRelevance).filter(*pro_parm).all()
    mantis_id_list = [MantisBugTable.project_id == i.mantis_id for i in pro_l if i.mantis_id != '0']
    Bug_parm.append(or_(*mantis_id_list))
    s_date += ' 00:00:00'
    e_date += ' 23:59:59'
    Bug_parm.append(MantisBugTable.date_submitted >= _ymdhms_to_timestamp(s_date))
    Bug_parm.append(MantisBugTable.date_submitted <= _ymdhms_to_timestamp(e_date))

    pro_bug_count = db.session.query(MantisProjectTable.name.label("name"),
                                     func.count(MantisBugTable.id).label("bug_count")
                                     ).outerjoin(MantisProjectTable, MantisBugTable.project_id == MantisProjectTable.id
                                                 ).filter(*Bug_parm).group_by(MantisProjectTable.id
                                                                              ).order_by("bug_count").all()
    personnel_bug_count = db.session.query(MantisUserTable.realname.label("dev_name"),
                                           func.count(MantisBugTable.id).label("bug_count")
                                           ).outerjoin(MantisUserTable, MantisBugTable.handler_id == MantisUserTable.id
                                                       ).filter(*Bug_parm).group_by(MantisBugTable.handler_id
                                                                                    ).order_by("bug_count").all()
    # .order_by(asc("bug_count"))
    data = {
        'demand_type': _pro_demand(page_data),
        'pro_bug': _bug_pro(pro_bug_count),
        # 'pro_ontime':1,
        # 'week_quality':1,
        'bug_personnel': _bug_personnel(personnel_bug_count)
    }

    return data


def _day(time):
    if time == '周':
        start = (datetime.now() + relativedelta(weeks=-1)).strftime("%Y-%m-%d")
        end = datetime.now().strftime("%Y-%m-%d")
    elif time == '月':
        start = (datetime.now() + relativedelta(months=-1)).strftime("%Y-%m-%d")
        end = datetime.now().strftime("%Y-%m-%d")
    else:
        start, end = time[0], time[1]
    return [start, end]


def _ymdhms_to_timestamp(str_time):
    """
    字符串时间格式转化成秒数时间戳
    :param str_time: "2019-5-10 23:40:00"
    :return: 秒数时间戳
    """
    # 先转换为时间数组
    timeArray = time.strptime(str_time, "%Y-%m-%d %H:%M:%S")
    # 转换为时间戳
    return int(time.mktime(timeArray))


def _pro_demand(pro_data):
    # print(pro_data)
    name = '需求类型统计'
    dl = [demand(i.ptype).name for i in pro_data]
    if len(dl) == 0:
        data = []
        name = '上周无测试、完成、上线项目'
    else:
        data = [
            {"value": dl.count('标准需求'), "name": '标准需求'},
            {"value": dl.count('验收需求'), "name": '验收需求'},
            {"value": dl.count('生产事故'), "name": '生产事故'},
            {"value": dl.count('线上bug'), "name": '线上bug'},
            {"value": dl.count('紧急发版'), "name": '紧急发版'}
        ]

    demand_type = {
        "name": name,
        "data": data
    }
    return demand_type


def _bug_pro(bug_data):
    # dl = [i.bug_count for i in bug_data]
    pro_bug = {}
    pro_bug["xAxis_type"] = [i.name for i in bug_data]
    pro_bug["legend_data"] = ["bug数量"]
    pro_bug["series_data"] = {"bug数量": [i.bug_count for i in bug_data]}
    if pro_bug["series_data"]["bug数量"] == []:
        pro_bug["legend_data"] = ["上周无该业务bug"]
    return pro_bug


def _bug_personnel(bug_data):
    personnel_bug = {}
    # print([i.bug_count for i in bug_data])
    personnel_bug["xAxis_type"] = [i.dev_name for i in bug_data]
    personnel_bug["series_data"] = {"bug数量": [i.bug_count for i in bug_data]}
    personnel_bug["legend_data"] = ["bug数量"]
    personnel_bug["series_data"] = {"bug数量": [i.bug_count for i in bug_data]}
    if personnel_bug["series_data"]["bug数量"] == []:
        personnel_bug["legend_data"] = ["上周无该业务bug"]
    return personnel_bug


def get_collect_question(data):
    """
    获取业务线问题
    :param data:
    :return:
    """
    collect_parm = [Collect.status != 0]
    date_time = _day(data['radio'])  # 周
    s_date = date_time[0]
    # e_date = date_time[1]
    # print(s_date,e_date)
    collect_parm.append(or_(Collect.begindate >= s_date, Collect.onlinedate >= s_date, Collect.enddate >= s_date))
    # collect_parm.append(Collect.onlinedate <= e_date)
    if data['group_name'] != '':  # 业务线
        # if data['group_name'] == '内容·运营':
        #     collect_parm.append(or_(Collect.group == '互动',
        #                             Collect.group == '资讯')
        #                         )
        # else:
            collect_parm.append(Collect.group == data["group_name"])

    page_data = db.session.query(Collect.pstatus, Collect.project, Collect.version, Collect.enddate, Collect.onlinedate,
                                 Collect.pquest,
                                 Collect.remark).filter(*collect_parm).all()

    response_dic = {}
    response_list = []
    if page_data:
        for i in page_data:
            response_dic['project'] = i.project
            response_dic['status'] = i.pquest
            response_dic['version'] = i.version
            response_dic['enddate'] = i.enddate
            response_dic['onlinedate'] = i.onlinedate
            response_dic['pquest'] = i.pquest
            if not i.pquest:
                response_dic['pquest'] = ""
            response_dic['remark'] = i.remark
            if not i.remark:
                response_dic['remark'] = ""
            response_list.append(response_dic.copy())
            response_dic.clear()
    response_dic['items'] = response_list
    response_dic['total'] = 10
    return response_dic



